<table class="form-table">
  <tbody>
    <!-- premium key -->
    <tr>
      <th scope="row">
        <label for="mailpoet_premium_key">
          <%= __('Premium License Key') %>
        </label>
        <p class="description">
          <%= __('This key is used for automatic upgrades of your Premium features and access to support.') %>
        </p>
      </th>
      <td>
        <div>
          <input
            type="text"
            class="regular-text"
            id="mailpoet_premium_key"
            name="premium[premium_key]"
            value="<%=- settings.premium.premium_key | default(settings.mta.mailpoet_api_key) -%>"
          />
          <a
            id="mailpoet_premium_key_verify"
            class="button-secondary"
          ><%= __('Verify') %></a>
        </div>
        <div
          class="mailpoet_premium_key_valid mailpoet_success_item mailpoet_success<% if not(settings.premium.premium_key) or not(premium_key_valid) %> mailpoet_hidden<% endif %>"
        >
          <%= __('Your Premium key has been successfully validated.') %>
        </div>
        <div
          class="mailpoet_premium_key_invalid mailpoet_error_item mailpoet_error<% if not(settings.premium.premium_key) or premium_key_valid %> mailpoet_hidden<% endif %>"
        >
          <%= __('Your Premium key is invalid.') %>
        </div>
        <div
          class="mailpoet_mss_key_valid mailpoet_success_item mailpoet_success<% if not(settings.mta.mailpoet_api_key) or not(mss_key_valid) %> mailpoet_hidden<% endif %>"
        >
          <%= __('Your MailPoet Sending Service key has been successfully validated.') %>
        </div>
        <div
          class="mailpoet_mss_key_invalid mailpoet_error_item mailpoet_error<% if not(settings.mta.mailpoet_api_key) or mss_key_valid %> mailpoet_hidden<% endif %>"
        >
          <%= __('Your MailPoet Sending Service key is invalid.') %>
        </div>
        <div
          class="mailpoet_premium_download mailpoet_spaced_block"
          <% if premium_plugin_installed or not(premium_key_valid) %>
            style="display: none;"
          <% endif %>
        >
          <a
            class="mailpoet_premium_install_link button-primary"
            href="<%= premium_install_url | default('#') %>"
          ><%= __('Install Premium now.') %>
          </a>
          <span>
            <%= __('[link]Read guide[/link] on how to install Premium.')
              |replaceLinkTags('http://beta.docs.mailpoet.com/article/194-instructions-to-install-the-premium-plugin', {'target' : '_blank'})
              |raw
            %>
           </span>
        </div>
        <div
          class="mailpoet_premium_activate mailpoet_spaced_block"
          <% if not(premium_plugin_installed) or premium_plugin_active or not(premium_key_valid) %>
            style="display: none;"
          <% endif %>
        >
          <span><%= __('You need to activate the MailPoet Premium plugin.') %></span>
          <a
            class="mailpoet_premium_activate_link button-primary"
            href="<%= premium_activate_url | default('#') %>"
          ><%= __('Activate Premium.') %></a>
        </div>
        <div
          class="mailpoet_mss_activate_notice mailpoet_spaced_block"
          <% if mss_active or not(mss_key_valid) %>
            style="display: none;"
          <% endif %>
        >
          <span>
            <%= __("Don't forget to activate the MailPoet Sending Service in the [link]Send with...[/link] tab above.")
              |replaceLinkTags('#mta')
              |raw
            %>
          </span>
        </div>
      </td>
    </tr>
  </tbody>
</table>

<script type="text/javascript">
  jQuery(function($) {
    $(function() {
      // verifying license key
      $('#mailpoet_premium_key_verify').on('click', function () {
        // get license key
        var key = $('#mailpoet_premium_key').val();

        if(key.length === 0) {
          // validation
          return MailPoet.Notice.error(
            '<%= __('Please specify a license key before validating it.') | escape('js') %>',
            { scroll: true }
          );
        }

        MailPoet.Modal.loading(true);

        var promise1 = verifyMailPoetPremiumKey(key);
        var promise2 = verifyMailPoetSendingServiceKey(key);

        // wait until both requests are completed before hiding the loading modal
        promise1.always(function() {
          promise2.always(function() {
            MailPoet.Modal.loading(false);
          });
        });
      });

      function verifyMailPoetPremiumKey(key) {
        $('.mailpoet_premium_key_valid, .mailpoet_premium_key_invalid').addClass('mailpoet_hidden');
        $('.mailpoet_premium_download, .mailpoet_premium_activate').hide();

        return MailPoet.Ajax.post({
          api_version: window.mailpoet_api_version,
          endpoint: 'services',
          action: 'checkPremiumKey',
          data: {
            key: key
          }
        }).done(function(response) {
          // Hide server error notices
          $('.mailpoet_notice_server').hide();
          $('.mailpoet_premium_key_valid').text(response.data.message);
          $('.mailpoet_premium_key_valid').removeClass('mailpoet_hidden');
          if (!response.meta.premium_plugin_installed) {
            $('.mailpoet_premium_install_link')
              .attr('href', response.meta.premium_install_url || '#');
            $('.mailpoet_premium_download').show();
          } else if (!response.meta.premium_plugin_active) {
            $('.mailpoet_premium_activate_link')
              .attr('href', response.meta.premium_activate_url || '#');
            $('.mailpoet_premium_activate').show();
          }
          MailPoet.trackEvent(
            'User has validated a Premium key',
            {
              'MailPoet Free version': window.mailpoet_version,
              'Premium plugin is active': response.meta.premium_plugin_active
            }
          );
        }).fail(function(response) {
          if (response.errors.length > 0) {
            $('.mailpoet_premium_key_invalid').text(
              response.errors.map(function(error) { return error.message; }).join(' ')
            );
            $('.mailpoet_premium_key_invalid').removeClass('mailpoet_hidden');
          }
          MailPoet.trackEvent(
            'User has failed to validate a Premium key',
            {
              'MailPoet Free version': window.mailpoet_version,
              'Premium plugin is active': !!window.mailpoet_premium_version
            }
          );
        });
      }

      function verifyMailPoetSendingServiceKey(key) {
        $('.mailpoet_mss_key_valid, .mailpoet_mss_key_invalid').addClass('mailpoet_hidden');
        $('.mailpoet_mss_activate_notice').hide();

        return MailPoet.Ajax.post({
          api_version: window.mailpoet_api_version,
          endpoint: 'services',
          action: 'checkMSSKey',
          data: {
            key: key
          }
        }).done(function(response) {
          // Hide server error notices
          $('.mailpoet_notice_server').hide();
          $('.mailpoet_mss_key_valid').text(response.data.message);
          $('.mailpoet_mss_key_valid').removeClass('mailpoet_hidden');
          updateMSSActivationUI();
        }).fail(function(response) {
          if (response.errors.length > 0) {
            $('.mailpoet_mss_key_invalid').text(
              response.errors.map(function(error) { return error.message; }).join(' ')
            );
            $('.mailpoet_mss_key_invalid').removeClass('mailpoet_hidden');
            updateMSSActivationUI();
          }
        });
      }

      $('.mailpoet_premium_install_link').on('click', function() {
        MailPoet.trackEvent(
          'User has installed the Premium plugin from Settings',
          {'MailPoet Free version': window.mailpoet_version}
        );
      });

      $('.mailpoet_premium_activate_link').on('click', function() {
        MailPoet.trackEvent(
          'User has activated the Premium plugin from Settings',
          {'MailPoet Free version': window.mailpoet_version}
        );
      });

    });
  });
</script>
